Ext.define('FirstMate.controller.Map',
				{
				extend : 'Ext.app.Controller',
				// stores: ['FirstMate.store.Tides'],
				views : [ 'FirstMate.view.Map' ],
				refs : {
					mainView : '#mainView',
					mapView : '#mapView',
					NWSForecastView : '#NWSforecastview'
				},
				
				launch : function() {
					
			        //if (!FirstMate.app.Marker){
					FirstMate.app.Marker = new google.maps.Marker({
						position: FirstMate.app.position,
						map: Ext.getCmp('extmap').getMap(),
						icon : 'app/resources/icons/sailing.png',
						visible: true,
						title : 'Drag me around to change the search area',
						draggable : true,
						raiseOnDrag : true
					});
					google.maps.event.addListener(FirstMate.app.Marker, 'dragend', function() { 
						console.log('DRAGEND');
						FirstMate.app.getController('Map').removeTidesMarkers();
						FirstMate.app.position = FirstMate.app.Marker.getPosition();
						FirstMate.app.Marker.setTitle(FirstMate.app.Marker.getPosition().toString());
						Ext.getCmp('extmap').getMap().setCenter(FirstMate.app.Marker.getPosition());
						FirstMate.app.bounds = FirstMate.app.getController('Map').getBounds(FirstMate.app.Marker.getPosition());
						Ext.getStore('tidesStationsStore').filterByGeoBounds(FirstMate.app.bounds);
						FirstMate.app.getController('Settings').setAppDate();
						 FirstMate.app.getController('Settings').getAsOfDateField().setValue(FirstMate.app.date);
						//Ext.getStore('tidesStore').loadAll(FirstMate.app.date);
						Ext.getStore('marineWeatherStore').loadWeather(FirstMate.app.position);
						FirstMate.app.getController('Map').addNOAAZonesLayer();
						FirstMate.app.getController('Map').addHRRadarLayer();
					});

					Ext.getStore('tidesStore').on('allTideDataLoaded',this.onTidesLoaded, this);
					Ext.getStore('tidesStore').on('allTideDataLoading',this.onTidesLoading, this);
					FirstMate.app.extMap = Ext.getCmp('extmap');
					 if (!Ext.device.Geolocation){
						 FirstMate.app.extMap.setGeo(FirstMate.app.geo);
					 }
					
					FirstMate.app.googleMap = FirstMate.app.extMap.getMap();
					FirstMate.app.getController('Map').hideLinks();
					
				},
				
				onUpdateLocation : function (){
				    	
				    	FirstMate.app.position = new google.maps.LatLng(FirstMate.app.geo.getLatitude(), 
				    													FirstMate.app.geo.getLongitude()
				    													);//4 decimals
				    	FirstMate.app.getController('Map').resetMap();

				},
				
				onLocationError: function (geo, bTimeout, bPermissionDenied, bLocationUnavailable, message){

						if(bTimeout){
				        	Ext.Msg.alert('Timeout problem accessing geolocation.', 'Please make sure geolocation is on', Ext.emptyFn);
				        }
				        if(bPermissionDenied){
				        	Ext.Msg.alert('Permissions problem accessing geolocation.', 'Please make sure geolocation is on', Ext.emptyFn);
				        }
				        if(bLocationUnavailable){
				        	Ext.Msg.alert('Geolocation unavailable.', 'Please make sure geolocation is on', Ext.emptyFn);
				        }
				        if(!(bTimeout||bPermissionDenied||bLocationUnavailable)){
				        	Ext.Msg.alert('Problem accessing geolocation.', 'Please make sure geolocation is on', Ext.emptyFn);
				        }
				        FirstMate.app.getController('Map').resetMap();
				    },
				 

			    resetMap : function () {
			    	
			    		FirstMate.app.date = FirstMate.app.useCurrentTime == 1 ? new Date() : FirstMate.app.date;
			   	   							
				   		FirstMate.app.Marker.setPosition(FirstMate.app.position);
				   		FirstMate.app.Marker.setTitle(FirstMate.app.Marker.getPosition().toString());
				   		Ext.getCmp('extmap').getMap().setCenter(FirstMate.app.Marker.getPosition());
						FirstMate.app.bounds = FirstMate.app.getController('Map').getBounds(FirstMate.app.Marker.getPosition());
						Ext.getStore('tidesStationsStore').filterByGeoBounds(FirstMate.app.bounds);
						FirstMate.app.getController('Settings').setAppDate();
						//Ext.getStore('tidesStore').loadAll(FirstMate.app.date);
						 FirstMate.app.getController('Settings').getAsOfDateField().setValue(FirstMate.app.date);
						Ext.getStore('marineWeatherStore').loadWeather(FirstMate.app.Marker.getPosition());
						FirstMate.app.getController('Map').hideLinks();
						FirstMate.app.getController('Map').addNOAAZonesLayer();
						FirstMate.app.getController('Map').addHRRadarLayer();	

			    },
								
				onTidesLoading : function(){
					
					if (stationCount  != 0) {
						var mapPanel = FirstMate.app.extMap;//Ext.ComponentQuery.query('map')[0];
						var stationCount =  Ext.getStore('tidesStationsStore').getCount();
						var loadColor = 'white';
						if (stationCount > 20){loadColor = 'yellow';}
						if (stationCount > 50){loadColor = 'red';}
						mapPanel.setMasked({xtype:'loadmask',
							 message:	'Loading tides data for ' + 
							 			'<span style = "color:' + loadColor + '">' + stationCount + '</span>' + 
							 			' stations'
						});
//						FirstMate.app.getController('Map').addNOAAZonesLayer();
//						FirstMate.app.getController('Map').addHRRadarLayer();	
					};

				},
				
				onTidesLoaded : function(store, records, success) {

					this.removeTidesMarkers();
					this.addTidesMarkers();
					FirstMate.app.extMap.setMasked(false);
					FirstMate.app.getController('Map').hideLinks();
					
				},
				
				addTidesMarkers : function() {

					var map = Ext.getCmp('extmap').getMap();
					var sr = ' ';
					FirstMate.app.tidesStore
							.each(function(record) {
								if (record.get("stationName") != sr) {
									sr = record.get("stationName");
									//console.log(sr);
									var position = new google.maps.LatLng(
											record.get("latitude"), record
													.get("longitude"));
									var iconType;
									if (record.get('type') == 'H') {
										iconType = 'up';
									} else {
										iconType = 'down';
									}
									;
									var imageIconPath = 'app/resources/icons/'
											+ iconType + '/marker-images';
									var image = new google.maps.MarkerImage(
											imageIconPath + '/image.png',
											new google.maps.Size(24, 24),
											new google.maps.Point(0, 0),
											new google.maps.Point(12, 24));

									var shadow = new google.maps.MarkerImage(
											imageIconPath + '/shadow.png',
											new google.maps.Size(40, 24),
											new google.maps.Point(0, 0),
											new google.maps.Point(12, 24));

									var shape = {
										coord : [ 16, 0, 18, 1, 19, 2, 20,
												3, 21, 4, 22, 5, 23, 6, 23,
												7, 23, 8, 23, 9, 23, 10,
												23, 11, 23, 12, 23, 13, 23,
												14, 23, 15, 23, 16, 23, 17,
												22, 18, 21, 19, 21, 20, 20,
												21, 18, 22, 17, 23, 6, 23,
												5, 22, 4, 21, 3, 20, 2, 19,
												1, 18, 1, 17, 0, 16, 0, 15,
												0, 14, 0, 13, 0, 12, 0, 11,
												0, 10, 0, 9, 0, 8, 0, 7, 1,
												6, 1, 5, 2, 4, 3, 3, 4, 2,
												5, 1, 7, 0, 16, 0 ],
										type : 'poly'
									};

									var marker = new google.maps.Marker({
										icon : image,
										shadow : shadow,
										shape : shape,
										map : map,
										position : position,
										title : record.get('stationName'),
										visible : true
									});

									FirstMate.app.tidesMarkers.push(marker);

									google.maps.event
											.addListener(
													marker,
													'click',
													function() {
														var time = record.get("time");
														var waterType = record.get("type") == 'L' ? '<span style="color:red">low water</span>'
																								  : '<span style="color:green">high water</span>';
														var totalMinutes = Math.floor((time.getTime() - FirstMate.app.date.getTime())/(1000 * 60));
														var wholeHours = Math.floor(totalMinutes/60);
														var wholeMinutes = totalMinutes%60;
														var height = (FirstMate.app.tideUnits == 'm'? Math.round(record.get("waterLevel") * 10)/10 : Math.round(record.get("waterLevel") * 328.08399)/100);
														
														
														
														if (FirstMate.app.weatherInfoWindow) {
															FirstMate.app.weatherInfoWindow.close();
														};
		
														if (FirstMate.app.tidesInfoWindow) {
															FirstMate.app.tidesInfoWindow.close();
														};

														
														FirstMate.app.tidesInfoWindow = new google.maps.InfoWindow(
																		{
																			content : '<center>' +
																					record.get("stationName")
																					+ '<br></br>'
																					+ waterType
																					+ ' in '
																					+ wholeHours
																					+ ' hrs ' 
																					+ wholeMinutes
																					+ ' min<br></br>'
																					+ (height > 0 ? '<span style="color:blue">' + height + '</span>'
																							  	 : '<span style="color:red">' + height + '</span>')
																					+ ' '
																					+ FirstMate.app.tideUnits
																					+ '<br></br>at '
																					+ ('00' + (time.getMonth() + 1)).slice(-2) 
																					+ '/'
																					+ ('00' + time.getDate()).slice(-2)
																					+ '/'
																					+ time.getFullYear()
																					+ ' '
																					+ ('00' + time.getHours()).slice(-2)
																					+ ':'
																					+ ('00' + time.getMinutes()).slice(-2)
																					+ '</center>'
																		}),map, marker;
														FirstMate.app.tidesInfoWindow.open(map,marker);
													});

								};
							});
				},
				
				removeTidesMarkers : function() {

					markers = FirstMate.app.tidesMarkers;
					for ( var i = 0; i < markers.length; i++) {
						markers[i].setMap(null);
					}
				},

				getBounds : function(position) {

					if (FirstMate.app.searchCircle != null) {
						FirstMate.app.searchCircle.setMap(null);
					}
					FirstMate.app.searchCircle = new google.maps.Circle({
						center : position,
						radius : FirstMate.app.searchUnits == 'km' ? FirstMate.app.searchRadius * 1000 : FirstMate.app.searchRadius * 1852,
						visible : false,
						clickable : false,
						fillOpacity : 0.05,
						strokeOpacity : 1,
						strokeColor : '#7CFC00',
						map : FirstMate.app.googleMap
					});
					return FirstMate.app.searchCircle.getBounds();
				},
				
				addNOAAZonesLayer : function() {

					if (FirstMate.app.NOAAZonesLayer != null){
						FirstMate.app.NOAAZonesLayer.setMap(null);
					} 	
					if (FirstMate.app.NOAAZonesLayerOn == 1){					
						FirstMate.app.NOAAZonesLayer = new google.maps.FusionTablesLayer({
						          query: {
							            select: 'ID, NAME',
							            from: '1398qV5hJBtDXW1zVLvk3twgdGuFuedn5r0mfA7VR',
							            orderBy: "ST_DISTANCE" +
							            "(LAT," +							            
							            "LATLNG(" + FirstMate.app.position.lat() + ", " + FirstMate.app.position.lng() + ")) " +
							            "LIMIT 1"
							          },
							      styles: [{
							        	    polygonOptions: {
							        	      fillColor: FirstMate.app.NOAAZonesLayerColor,
							        	      fillOpacity: FirstMate.app.NOAAZonesLayerOpacity
							        	    }
							        	  	}],
						          map: FirstMate.app.googleMap,
						          clickable : false
						});
						
						var q = FirstMate.app.NOAAZonesLayer.query;
						var sqlQuery = "select " + q.select +
						" from " + q.from + 
						" ORDER BY " + q.orderBy;
						var theUrl = 'https://www.googleapis.com/fusiontables/v1/query?sql=' + sqlQuery + '&key=' + FirstMate.app.fusionTablesAPIKey;
						var xmlHttp = null;
					    xmlHttp = new XMLHttpRequest();
					    xmlHttp.open( "GET", theUrl, false );
					    xmlHttp.send( null );
					    var info = eval ( "(" + xmlHttp.responseText + ")" );
					    var zone = info.rows[0];
//					    console.log(zone);
					    Ext.getCmp('NWSForecastView').updateView(zone);
					    
             	   }
				},
				

				addHRRadarLayer : function() {
	
						if (FirstMate.app.HRRadarLayerOn == 1){

							var map = FirstMate.app.googleMap;
							var rtv = new RTVMapType(map);
							FirstMate.app.HRRadarLayer = rtv;						
						    map.overlayMapTypes.setAt(0,rtv);
							
							rtv.setOpacity(FirstMate.app.HRRadarLayerOpacity);
							rtv.setColorScheme(1);
							rtv.setResolution(FirstMate.app.HRRadarLayerResolution);
							rtv.setHourly(true);
							//rtv.setLatestTimestampAtLatLng(FirstMate.app.position);
							//rtv.setTimestamp(FirstMate.app.date.getTime());
							rtv.setLatestTimestampAtLatLng(FirstMate.app.position, function(timestamp,metadata){	
								//FirstMate.app.getController('Settings').getRadarTimestampField().setValue(new Date(timestamp*1000));
								FirstMate.app.getController('Settings').getRadarTimestampField().setValue(new Date(timestamp*1000));
							});
							//This method returns data to a callback function. 
							//The current resolution and process (averaged|hourly) are used to identify availability. 
							//The callback function will accept 2 parameters: 
							//(int timestamp, object metadata). 
							//The metadata object will be either of the form 
							//{"error":_message_}, or 
							//{"lat":_lat_,"lng":_lng_,"distance":_arc_degrees_,"latest":_timestamp_}. 
							//This method alters the state of the displayed map and updates it with the latest available tile set 
							//nearest the provided GLatLng, within +/-1 degree lat and/or lon							
	             	   }
				},		      
			      
				
				addKmlLayer : function() {

					if (FirstMate.app.KmlLayer != null){
						FirstMate.app.KmlLayer.setMap(null);
					} 	
					if (FirstMate.app.KmlLayerOn == 1){
						FirstMate.app.KmlLayer = new google.maps.KmlLayer({
			        		preserveViewport: true,
			        		suppressInfoWindows: false,
			        		map : FirstMate.app.googleMap,
			        		url : FirstMate.app.KmlLayerUrl
			    		});
						FirstMate.app.KmlLayer.set('opacity', FirstMate.app.KmlLayerOpacity);
             	   }
				},
				
				addWeatherLayer : function() {

					if (FirstMate.app.weatherLayer != null){
						FirstMate.app.weatherLayer.setMap(null);
					}					
					if (FirstMate.app.weatherLayerOn == 1){
						FirstMate.app.weatherLayer = new google.maps.weather.WeatherLayer({
							temperatureUnits: FirstMate.app.tideUnits == 'm'? google.maps.weather.TemperatureUnit.CELSIUS : google.maps.weather.TemperatureUnit.FAHRENHEIT,
			        		windSpeedUnits : FirstMate.app.tideUnits == 'm'? google.maps.weather.TemperatureUnit.KILOMETERS_PER_HOUR : google.maps.weather.WindSpeedUnit.MILES_PER_HOUR,
			        		suppressInfoWindows : true,
			        		map : FirstMate.app.googleMap
						});
						FirstMate.app.weatherLayerListener = 
							google.maps.event.addListener(FirstMate.app.weatherLayer, 'click', FirstMate.app.getController('Map').createWeatherInfoWindow);
             	   }
				},
				
				addCloudLayer : function() {

					if (FirstMate.app.cloudLayer != null){
						FirstMate.app.cloudLayer.setMap(null);
					} 					
					if (FirstMate.app.cloudLayerOn == 1){
						FirstMate.app.cloudLayer = new google.maps.weather.CloudLayer();
						FirstMate.app.cloudLayer.setMap(FirstMate.app.googleMap);
					}					
				},
				
				addBicycleLayer : function() {

					if (FirstMate.app.bicycleLayer != null){
						FirstMate.app.bicycleLayer.setMap(null);
					}					
					if (FirstMate.app.bicycleLayerOn == 1){
						FirstMate.app.bicycleLayer = new google.maps.BicyclingLayer();
						FirstMate.app.bicycleLayer.setMap(FirstMate.app.googleMap);						
					}					
				},
				
				createWeatherInfoWindow : function(weatherClick) {

					if (FirstMate.app.tidesInfoWindow){
						FirstMate.app.tidesInfoWindow.close();
					}
					if (FirstMate.app.weatherInfoWindow){
						FirstMate.app.weatherInfoWindow.close();
					}
					FirstMate.app.weatherInfoWindow = new google.maps.InfoWindow(
							{
								content : weatherClick.infoWindowHtml,
								position : weatherClick.latLng 
							});
					FirstMate.app.weatherInfoWindow.open(FirstMate.app.googleMap);
					FirstMate.app.getController('Map').hideLinks();
					
				},
				
				hideLinks : function (){
					
					var links = Ext.DomQuery.select('div > a, a');
					Ext.Array.each(links, function(el) {
						//console.log("hiding " + el);    
						el.hidden = true;
						el.href = "";
						el.title = "Click to reload";
					});
					
				}
});
